﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Ccr.Core;
using NUnit.Framework;
using XcoAppSpaces.Core;

namespace test.XcoAppSpaces.Core.Test_Single_Ports_of_Remote_Worker
{
    [TestFixture]
    public class testSinglePortUsageOnRemoteWorker
    {
        [Test]
        public void Call_single_port_on_remote_worker_with_causality()
        {
            using(XcoAppSpace server = new XcoAppSpace("tcp.port=8001"))
			using (XcoAppSpace client = new XcoAppSpace("tcp.port=8002"))
            {
                server.RunWorker<PWorker, MyWorker>("myworker");

                PWorker w;
				w = client.ConnectWorker<PWorker>(string.Format("localhost:{0}/myworker", 8001)); //new Uri(string.Format("xco://localhost:{0}/myworker", 8001)));

                Port<string> pResults = new Port<string>();
                Port<Exception> pEx = new Port<Exception>();
                Arbiter.Activate(
                    client.DefaultDispatcherQueue,
                    Arbiter.Receive(
                        true,
                        pEx,
                        Console.WriteLine
                        )
                    );
                Dispatcher.AddCausality(new Causality("cx", pEx, pResults));

                w.Post(10);
                Assert.AreEqual("10", pResults.TestSync(1500));

                w.Post("hello");
                Assert.AreEqual("hello", pResults.TestSync(1500));

                w.P0.Post(99);
                Assert.AreEqual("99", pResults.TestSync(1500));

            	Dispatcher.RemoveCausality("cx");
            }
        }


        public class PWorker : PortSet<int, string>{}

        public class MyWorker : PWorker
        {
            [XcoConcurrent]
            void ProcessInt(int n)
            {
                Console.WriteLine(n);

                ICausality c = Dispatcher.ActiveCausalities.First();
                Port<string> pReturn = (Port<string>) c.CoordinationPort;
                pReturn.Post(n.ToString());
            }

            [XcoConcurrent]
            void ProcessString(string s)
            {
                Console.WriteLine(s);
                Dispatcher.ActiveCausalities.First().CoordinationPort.PostUnknownType(s);
            }
        }
    }
}
